package com.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.entity.AllData;
import com.util.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.util.DataSourceUtils;
import com.entity.News;
@WebServlet("/newslist")
public class NewslistServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<AllData> items = new ArrayList<>();
        String sql = "SELECT DISTINCT cid,tid,title FROM AllData";
        try(Connection conn = DataSourceUtils.getConnection();
            PreparedStatement st = conn.prepareStatement(sql);
            ResultSet rs = st.executeQuery()) {
            while (rs.next()) {
                AllData item = new AllData(rs.getInt("cid"), rs.getInt("tid"), rs.getString("title"));
                items.add(item);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        List<News> items2 = new ArrayList<>();
        String sql2 = "SELECT * FROM News";
        try(Connection conn2 = DataSourceUtils.getConnection();
            PreparedStatement st2 = conn2.prepareStatement(sql2);
            ResultSet rs2 = st2.executeQuery()) {
            while (rs2.next()) {
                News item = new News(rs2.getInt("id"), rs2.getString("name"), rs2.getString("content"),rs2.getTimestamp("date"));
                items2.add(item);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        req.setAttribute("items", items);
        req.setAttribute("items2", items2);
        req.getRequestDispatcher("/WEB-INF/jsp/newslist.jsp")
                .forward(req, resp);
    }
}